﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using StriveEngine;
using StriveEngine.Core;
using StriveEngine.Tcp.Server;
using System.Net;
using UtilHelper;
using MessagePush;

namespace StriveEngine.SimpleDemoServer
{
    /*
     * 更多实用组件请访问 www.oraycn.com 或 QQ：168757008。
     * 
     * ESFramework 强悍的通信框架、P2P框架、群集平台。OMCS 简单易用的网络语音视频框架。MFile 语音视频录制组件。StriveEngine 轻量级的通信引擎。
     */
    public partial class cswMsg : Form
    {
        private ITcpServerEngine tcpServerEngine;
        private bool hasTcpServerEngineInitialized;
        private List<Users> uplist = new List<Users>();
        private ClassDAL dal = new ClassDAL();
        public cswMsg()
        {
            InitializeComponent();


     //       string msg = @"{"
     //+ "\"fCustomId\":\"100002\","
     //+ "\"fName\":\"中国超市网\","
     //+ "\"fAvatar\":\"../img/avtar.png\","
     //+ "\"sCustomId\":\"000000\","
     //+ "\"sName\":\"接收人\","
     //+ "\"sAvatar\":\"../img/avtar.png\","
     //+ "\"msgTime\":\"" + UDateTime.ConvertDateTimeInt(DateTime.Now).ToString() + "\","
     //+ "\"type1\":\"1\","
     //+ "\"type2\":\"2\","
     //+ "\"msgRedtime\":\"\","
     //+ "\"bussCode\":\"\","
     //+ "\"status\":\"1\","
     //+ "\"content\": {"
     //  + "\"msgType\":\"2\","
     //  + "\"texts\":\"你好啊,鲍是个小猪！\","
     //  + "\"img\":\"\""
     //  + "}"
     //+ "}";

     //       PushMessage.PushMessageToSingle("Aug8SBHS1GQLw1HMmw67uWo9bVqEmVQqikNz5C6cYXmU", "大龙标题", "通知栏描述", msg, "", "", "1");
        }
        //启动监听
        private void button1_Click(object sender, EventArgs e)
        {
            StriveEngine.GlobalUtil.SetAuthorizedUser("xiangshangsp", "xssp0817");
            try
            {
                
                if (this.tcpServerEngine == null)
                {
                   
                    this.tcpServerEngine = NetworkEngineFactory.CreateTextTcpServerEngine(int.Parse(this.textBox_port.Text), new DefaultTextContractHelper("\0"));//DefaultTextContractHelper是StriveEngine内置的ITextContractHelper实现。使用UTF-8对EndToken进行编码。 
                }

                if (this.hasTcpServerEngineInitialized)
                {
                    this.tcpServerEngine.ChangeListenerState(true);
                }
                else
                {
                    this.InitializeTcpServerEngine();
                }
                this.ShowListenStatus();
                //创建一个timer
                //System.Timers.Timer timer = new System.Timers.Timer();
                //timer.AutoReset = true;
                //timer.Enabled = true;
                //timer.Interval = 10000;
                //timer.Elapsed += timer_Elapsed;
                //timer.Start();
                Timer Timer1 = new Timer();     //创建Timer，名为Timer1。
                Timer1.Tick += Timer1_Tick;    //添加Timer1事件
                Timer1.Interval = 1000 * 60;
                Timer1.Start();   //启动Timer1

                //推送
                Environment.SetEnvironmentVariable("needDetails", "true");

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
                UDateTime.LogResult("错误消息为:" + ee.Message + ",方法为:button1_Click");
            }
        }
        //同步时间
        void Timer1_Tick(object sender, EventArgs e)
        {
            for (int i = 0; i < uplist.Count; i++)
            {
                UMessage u = new UMessage();
                u.type1 = "3"; //聊天消息
                u.type2 = "2"; //时间
                Content c = new Content();
                c.msgType = "2"; //内容
                u.content = c;
                u.sCustomId = uplist[i].code;
                u.msgTime = UDateTime.ConvertDateTimeInt(DateTime.Now).ToString();
                faMessage(uplist[i].code, JsonHelper.GetJson(u));
            }
            label4.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");
        }
        //同步时间
        //void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        //{
        //    label4.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        //}
        //初始化
        private void InitializeTcpServerEngine()
        {
            this.tcpServerEngine.ClientCountChanged += new CbDelegate<int>(tcpServerEngine_ClientCountChanged);
            this.tcpServerEngine.ClientConnected += new CbDelegate<System.Net.IPEndPoint>(tcpServerEngine_ClientConnected);
            this.tcpServerEngine.ClientDisconnected += new CbDelegate<System.Net.IPEndPoint>(tcpServerEngine_ClientDisconnected);
            this.tcpServerEngine.MessageReceived += new CbDelegate<IPEndPoint, byte[]>(tcpServerEngine_MessageReceived);
            this.tcpServerEngine.Initialize();
            this.hasTcpServerEngineInitialized = true;
        }
        //改变监听按钮状态
        private void ShowListenStatus()
        {
            this.button_StopListen.Enabled = this.tcpServerEngine.IsListening ? true : false;
            this.button_StartListen.Enabled = this.tcpServerEngine.IsListening ? false : true;
            this.button_Close.Enabled = this.tcpServerEngine.IsListening ? true : false;
            this.textBox_port.ReadOnly = true;
            this.button_Send.Enabled = this.tcpServerEngine.IsListening ? true : false;
            this.toolStripLabel_Port.Text = this.tcpServerEngine.IsListening ? this.tcpServerEngine.Port.ToString() : null;
        }
        //监听消息
        void tcpServerEngine_MessageReceived(IPEndPoint client, byte[] bMsg)
        {
            string msg = System.Text.Encoding.UTF8.GetString(bMsg); //消息使用UTF-8编码
            msg = msg.Substring(0, msg.Length - 1); //将结束标记"\0"剔除
            //刷新消息列表
            this.ShowClientMsg(client, msg);

            // this.tcpServerEngine.PostMessageToClient(client, bMsg);

        }
        //下线提醒
        void tcpServerEngine_ClientDisconnected(System.Net.IPEndPoint ipe)
        {
            string msg = string.Format("{0} 下线", ipe);
            this.ShowEvent(msg);
            for (int i = 0; i < uplist.Count; i++)
            {
                Users u = uplist[i];
                //存在
                if (u.name.IndexOf(ipe.ToString()) != -1)
                {
                    uplist.RemoveAt(i);
                }
            }
        }
        //上线提醒
        void tcpServerEngine_ClientConnected(System.Net.IPEndPoint ipe)
        {
            string msg = string.Format("{0} 上线", ipe);
            this.ShowEvent(msg);
        }

        //在线客户端数量
        void tcpServerEngine_ClientCountChanged(int count)
        {
            this.ShowConnectionCount(count);
        }
        //显示最新上线客户端
        private void ShowEvent(string msg)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new CbDelegate<string>(this.ShowEvent), msg);
            }
            else
            {
                this.toolStripLabel_event.Text = msg;
            }
        }
        //消息列表
        private void ShowClientMsg(IPEndPoint client, string msg)
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.BeginInvoke(new CbDelegate<IPEndPoint, string>(this.ShowClientMsg), client, msg);
                }
                else
                {
                    string customId = "";
                    //连接customId=100010\0
                    if (msg.IndexOf("连接customId=") != -1) //上线消息
                    {
                        customId = msg.Split('=')[1].ToString();
                        //加入
                        Users user = new Users()
                        {
                            code = customId,
                            name = client.ToString() + "客户:" + customId
                        };
                        Users user_b = uplist.Find(delegate (Users bu)
                        {
                            return bu.code == user.code;
                        });

                        if (user_b != null)
                        {
                            if (user_b.name != user.name)
                            {
                                uplist.Remove(user_b);
                                uplist.Add(user);
                            }
                        }
                        else
                        {
                            uplist.Add(user);
                        }
                        //连接上后发同步时间信息
                        UMessage u = new UMessage();
                        u.type1 = "3";
                        u.type2 = "2";
                        Content c = new Content();
                        c.msgType = "2";
                        u.content = c;
                        u.sCustomId = customId;
                        u.msgTime = UDateTime.ConvertDateTimeInt(DateTime.Now).ToString();
                        faMessage(customId, JsonHelper.GetJson(u));
                    }
                    else
                    {
                        //业务消息  
                        //1.解析消息 

                        UMessage uMessage = JsonHelper.ParseFormJson<UMessage>(msg);
                        //转发消息
                        faMessage(uMessage.sCustomId, msg);

                    }
                    //展示
                    ListViewItem item = new ListViewItem(new string[] { DateTime.Now.ToString(), client.ToString(), msg });
                    this.listView1.Items.Insert(0, item);
                }
            }
            catch (Exception ex)
            {
                //UDateTime.LogResult("错误消息为:" + msg + ",方法为:ShowClientMsg");
            }
        }
        //统计在线客户端数量
        private void ShowConnectionCount(int clientCount)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new CbDelegate<int>(this.ShowConnectionCount), clientCount);
            }
            else
            {
                this.toolStripLabel_clientCount.Text = "在线数量： " + clientCount.ToString();
            }
        }
        //发送消息
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                Users user = (Users)this.comboBox1.SelectedItem;
                string name = user.name;
                string comText = name.Substring(0, name.IndexOf("客户"));
                IPEndPoint client = null;
                List<IPEndPoint> list = this.tcpServerEngine.GetClientList();
                foreach (IPEndPoint f in list)
                {
                    if (f.ToString() == comText)
                    {
                        client = f;
                        break;
                    }
                }
                if (client == null)
                {
                    MessageBox.Show("没有选中任何在线客户端！");
                    return;
                }

                if (!this.tcpServerEngine.IsClientOnline(client))
                {
                    MessageBox.Show("目标客户端不在线！");
                    return;
                }

                string msg = this.textBox_msg.Text + "\0";// "\0" 表示一个消息的结尾
                byte[] bMsg = System.Text.Encoding.UTF8.GetBytes(msg);//消息使用UTF-8编码
                this.tcpServerEngine.SendMessageToClient(client, bMsg);
            }
            catch (Exception ee)
            {
              //  MessageBox.Show(ee.Message);
               // UDateTime.LogResult("错误消息为:" + this.textBox_msg.Text + "\0" + ",方法为:button2_Click");
            }
        }
        //自动转发消息
        private void faMessage(string code, string msg)
        {
            string status = "2";//已读
            try
            {
                IPEndPoint client = null;
                Users user = uplist.Find(delegate (Users u)
                {
                    return u.code == code;
                });
                if (user != null)
                {
                    string name = user.name;
                    string comText = name.Substring(0, name.IndexOf("客户"));

                    List<IPEndPoint> list = this.tcpServerEngine.GetClientList();
                    foreach (IPEndPoint f in list)
                    {
                        if (f.ToString() == comText)
                        {
                            client = f;
                            break;

                        }
                    }
                }
                else
                {
                    //不在线
                    UMessage u = JsonHelper.ParseFormJson<UMessage>(msg);
                    //推送给对方，未读
                    status = "1";
                    u.status = status;
                    //推送
                    string title = "聊天新消息";
                    string tzContent = u.content.texts;
                    string content = msg;
                    string logo = "";
                    string wllogo = "";
                    DataSet dscc = dal.getDataSet("select * from t_custom where customId=" + u.sCustomId);
                    if (dscc.Tables[0] != null && dscc.Tables[0].Rows.Count > 0)
                    {
                        PushMessage.PushMessageToSingle(dscc.Tables[0].Rows[0]["cid"].ToString(), title, tzContent, content, logo, wllogo, dscc.Tables[0].Rows[0]["cidLx"].ToString());
                    }
                    //插入数据库
                    int ret = addMessage(u);
                }
                if (client != null)
                {
                    // MessageBox.Show("没有选中任何在线客户端！");
                    UMessage u = JsonHelper.ParseFormJson<UMessage>(msg);
                    if (!this.tcpServerEngine.IsClientOnline(client))
                    {
                        // MessageBox.Show("目标客户端不在线！");
                        //推送给对方，未读
                        status = "1";
                        u.status = status;
                        //推送
                        string title = "聊天新消息";
                        string tzContent = u.content.texts;
                        string content = msg;
                        string logo = "";
                        string wllogo = "";
                        DataSet dscc = dal.getDataSet("select * from t_custom where customId=" + u.sCustomId);
                        if (dscc.Tables[0] != null && dscc.Tables[0].Rows.Count > 0)
                        {
                            PushMessage.PushMessageToSingle(dscc.Tables[0].Rows[0]["cid"].ToString(), title, tzContent, content, logo, wllogo, dscc.Tables[0].Rows[0]["cidLx"].ToString());
                        }
                    }
                    else
                    {
                        u.status = status;
                        u.msgRedtime = UDateTime.ConvertDateTimeInt(DateTime.Now).ToString();
                        msg = JsonHelper.GetJson<UMessage>(u);
                        msg = msg + "\0";// "\0" 表示一个消息的结尾
                        byte[] bMsg = System.Text.Encoding.UTF8.GetBytes(msg);//消息使用UTF-8编码
                        this.tcpServerEngine.SendMessageToClient(client, bMsg);

                    }
                    //插入数据库
                    int ret = addMessage(u);
                }

            }
            catch (Exception ee)
            {
              //  MessageBox.Show(ee.Message);
                //UDateTime.LogResult("错误消息为:" + msg + ",方法为:faMessage");
            }
        }
        //停止监听
        private void button_StopListen_Click(object sender, EventArgs e)
        {
            if (!this.tcpServerEngine.IsListening)
            {
                return;
            }
            this.tcpServerEngine.ChangeListenerState(false);
            this.ShowListenStatus();
        }

        //关闭监听
        private void button_Close_Click(object sender, EventArgs e)
        {
            this.tcpServerEngine.CloseAllClient();
            this.tcpServerEngine.Dispose();
            this.ShowListenStatus();
            this.textBox_port.ReadOnly = false;
            this.textBox_port.SelectAll();
            this.textBox_port.Focus();
            this.hasTcpServerEngineInitialized = false;
            this.tcpServerEngine = null;
        }

        //窗体关闭前发生事件
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //窗体关闭原因为单击"关闭"按钮或Alt+F4
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;           //取消关闭操作 表现为不关闭窗体
                this.Hide();               //隐藏窗体
            }
        }
        //"显示窗体"单击事件
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Show();                                //窗体显示
            this.WindowState = FormWindowState.Normal;  //窗体状态默认大小
            this.Activate();                            //激活窗体给予焦点
        }
        //"隐藏窗体"单击事件
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            this.Hide();                      //隐藏窗体
        }
        //"退出"单击事件
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            //点击"是(YES)"退出程序
            if (MessageBox.Show("确定要退出程序?", "安全提示",
                        System.Windows.Forms.MessageBoxButtons.YesNo,
                        System.Windows.Forms.MessageBoxIcon.Warning)
                == System.Windows.Forms.DialogResult.Yes)
            {
                notifyIcon1.Visible = false;   //设置图标不可见
                this.Close();                  //关闭窗体
                this.Dispose();                //释放资源
                Application.Exit();            //关闭应用程序窗体
            }
        }
        //鼠标左键图标事件
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            //点击鼠标"左键"发生
            if (e.Button == MouseButtons.Left)
            {
                this.Visible = true;                        //窗体可见
                this.WindowState = FormWindowState.Normal;  //窗体默认大小
                this.notifyIcon1.Visible = true;            //设置图标可见
            }
        }
        //查看在线列表
        private void comboBox1_DropDown(object sender, EventArgs e)
        {

            // List<IPEndPoint> list = this.tcpServerEngine.GetClientList();
            // this.comboBox1.DataSource = list;

            comboBox1.DataSource = null;
            //绑定数据源
            comboBox1.DataSource = uplist;
            comboBox1.DisplayMember = "name";
            comboBox1.ValueMember = "code";
        }

        //把消息插入数据库
        private int addMessage(UMessage u)
        {
            int ret = 0;
            if (u.type2 == "1")
            {
                string sql = "insert into TB_message(fCustomId,fName,fAvatar,sCustomId,sAvatar,sName,msgTime,msgRedtime,type1,type2,bussCode,status,texts,msgType,img)" +
               " values('" + u.fCustomId + "','" + u.fName + "','" + u.fAvatar + "','" + u.sCustomId + "','" + u.sAvatar + "','" + u.sName + "','"
               + u.msgTime + "','" + u.msgRedtime + "','" + u.type1 + "','" + u.type2 + "','" + u.bussCode + "','" + u.status + "','"
               + u.content.texts + "','" + u.content.msgType + "','" + u.content.img + "')";
                //执行
                ret = dal.Execute(sql);
            }
            return ret;
        }
    }

}
